<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('上市项目')" prop="listedId">
            <el-select v-model="form.listedId" filterable :placeholder="$t('请选择')" :disabled="form.id!==undefined" @change="selectListDeal()">
              <el-option
                v-for="item in listedOptions"
                :key="item.id"
                :label="item.dealName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('证券代码')" prop="stockCode">
            <el-input v-model="form.stockCode" :placeholder="$t('证券代码')" disabled show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('我方持有总股数(万股)')" prop="shareHold">
            <Money v-model="form.shareHold" :placeholder="$t('我方持有总股数(万股)')" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('持股比例(%)')" prop="shareRate">
            <Ratio v-model="form.shareRate" :placeholder="$t('持股比例(%)')" disabled />
          </el-form-item>
        </el-col>
        <el-col v-if="noticeShow" :span="12">
          <el-form-item :label="$t('公告')" prop="noticeId">
            <el-select v-model="form.noticeId" filterable :placeholder="$t('请选择')" @change="selectNotice()">
              <el-option
                v-for="item in noticeOptions"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="noticeShow" :span="12">
          <el-form-item :label="$t('减持股数不超过(万股)')" prop="shareNotExceeding">
            <Money v-model="form.shareNotExceeding" :placeholder="$t('减持股数不超过(万股)')" disabled />
          </el-form-item>
        </el-col>
        <el-col v-if="noticeShow" :span="12">
          <el-form-item :label="$t('减持比例不超过(%)')" prop="rateNotExceeding">
            <Ratio v-model="form.rateNotExceeding" unit="rate" :placeholder="$t('减持比例不超过(%)')" disabled />
          </el-form-item>
        </el-col>
        <el-col v-if="noticeShow" :span="12">
          <el-form-item :label="$t('预计公告发布日期')" prop="releaseDate">
            <el-date-picker
              v-model="form.releaseDate"
              disabled
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('预计公告发布日期')"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="noticeShow" :span="12">
          <el-form-item :label="$t('预计减持日期')" prop="reducingDate">
            <el-input v-model="form.reducingDate" :placeholder="$t('预计减持日期')" disabled show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
      </el-row>
      <!--减持明细-->
      <div style="margin-top: 20px;">
        <div class="area-header">
          <span class="area-header-title">{{ $t('实际减持明细维护') }}</span>
        </div>
        <el-table :data="form.detailList" border class="nowrapTable formTable" style="width: 100%">
          <el-table-column :label="$t('序号')" type="index" align="center" fixed show-overflow-tooltip width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('证券账号')" align="center" fixed show-overflow-tooltip min-width="280">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('证券账号') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.securityId'" :rules="dataRules.securityId">
                <el-select v-model="scope.row.securityId" disabled>
                  <el-option
                    v-for="dict in securityOptions"
                    :key="dict.id"
                    :label="dict.securityLabel"
                    :value="dict.id"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('实际减持总金额') + $t('金额单位')" align="center" min-width="180">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('实际减持总金额') }}{{ $t('金额单位') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.totalSubAmount'" :rules="dataRules.totalSubAmount">
                <Money v-model="scope.row.totalSubAmount" :placeholder="$t('实际减持总金额') + $t('金额单位')" unit="w" @change="calcSubPrice(scope.$index)" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('实际减持总股数(万股)')" align="center" min-width="180">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('实际减持总股数(万股)') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.totalSubShare'" :rules="dataRules.totalSubShare">
                <Money v-model="scope.row.totalSubShare" :placeholder="$t('实际减持总股数')" @change="calcSubPrice(scope.$index)" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('减持均价(元/股)')" align="center" min-width="180">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('减持均价(元/股)') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.subPrice'" :rules="dataRules.subPrice">
                <Money v-model="scope.row.subPrice" :placeholder="$t('减持均价(元/股)')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('减持税费') + $t('金额单位')" align="center" min-width="180">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('减持税费') }}{{ $t('金额单位') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.subTaxe'" :rules="dataRules.subTaxe">
                <Money v-model="scope.row.subTaxe" :placeholder="$t('减持税费') + $t('金额单位')" unit="w" @change="calcSubFeeRate(scope.$index)" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('减持费率(%)')" align="center" min-width="160">
            <template slot-scope="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.subFeeRate'">
                <Ratio v-model="scope.row.subFeeRate" :placeholder="$t('减持费率(%)')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('交易方式')" align="center" min-width="160">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('交易方式') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.tradingWay'" :rules="dataRules.tradingWay">
                <dictSelect
                  v-model="scope.row.tradingWay"
                  :clearable="true"
                  dictionary="listed_trading_way"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('减持日期')" align="center" min-width="160">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('减持日期') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.subDate'" :rules="dataRules.subDate">
                <DatePicker v-model="scope.row.subDate" :placeholder="$t('减持日期')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('交易对手')" align="center" min-width="160">
            <template slot-scope="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.opponentId'">
                <el-select v-model="scope.row.opponentId" clearable size="small">
                  <el-option
                    v-for="dict in opponentOptions"
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.id"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!--历史股票减持-->
      <div style="margin-top: 20px;">
        <div class="area-header">
          <span class="area-header-title">{{ $t('股票历史减持信息') }}</span>
        </div>
        <el-table v-loading="historyLoading" :data="historyDataList" border>
          <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
            <template slot-scope="scope">
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('上市项目')" align="center" prop="dealName" show-overflow-tooltip min-width="180" />
          <el-table-column :label="$t('证券代码')" align="center" prop="stockCode" show-overflow-tooltip min-width="150" />
          <el-table-column :label="$t('证券账号')" align="center" prop="securityAccount" show-overflow-tooltip min-width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.securityAccount }} - {{ scope.row.securityName }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('实际减持总金额') + $t('金额单位')" align="center" prop="totalSubAmount" width="150">
            <template slot-scope="scope">
              <span>{{ moneyFormat(scope.row.totalSubAmount, 'w') }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('实际减持总股数(万股)')" align="center" prop="totalSubShare" width="160">
            <template slot-scope="scope">
              <span>{{ moneyFormat(scope.row.totalSubShare) }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('减持均价(元/股)')" align="center" prop="subPrice" width="150">
            <template slot-scope="scope">
              <span>{{ moneyFormat(scope.row.subPrice) }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('减持比例(%)')" align="center" prop="subShareRate" width="150">
            <template slot-scope="scope">
              <span>{{ moneyFormat(scope.row.subShareRate) }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('交易方式')" align="center" prop="tradingWay" show-overflow-tooltip width="140" :formatter="tradingWayFormat" />
          <el-table-column :label="$t('减持日期')" align="center" prop="subDate" width="150">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.subDate) }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="historyTotal>0"
          :total="historyTotal"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="historyDataList"
        />
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <FormBtn ref="formBtn" has-permi="listed:shareSub" :bus-data="form" :btn-hide="btnHide" :menu-key="menuKey" />
    </div>
  </div>
</template>

<script>
import { listHistory } from '@/api/deal/listed/shareSub/listedShareSubDetail'
import { getListedDeal, listListedDeal } from '@/api/deal/listed/base/listedDeal'
import { getListedReducingNotice, listListedReducingNotice } from '@/api/deal/listed/reducing/listedReducingNotice'
import { listListedSecurity } from '@/api/deal/listed/security/listedSecurity'
import { listListedBusinessOpponent } from '@/api/deal/listed/businessOpponent/listedBusinessOpponent'
import { listListedPositionHold } from '@/api/deal/listed/position/listedPositionHold'
import { saveListedShareSub, getListedShareSub } from '@/api/deal/listed/shareSub/listedShareSub'

export default {
  data() {
    return {
      // 菜单标识
      menuKey: 'listed_share_sub',
      // 表单参数
      form: {
        detailList: []
      },
      // 是否隐藏保存按钮
      btnHide: false,
      // 是否隐藏其它按钮
      otherBtnHide: false,
      // 遮罩层
      loading: false,
      // 表单校验
      rules: {
        listedId: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }],
        noticeId: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }]
      },
      // 减持明细表单校验
      dataRules: {
        securityAccount: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        totalSubAmount: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        totalSubShare: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        subPrice: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        subTaxe: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        tradingWay: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }],
        subDate: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }]
      },
      // 交易方式字典
      tradingWayOptions: [],
      // 股票历史减持加载
      historyLoading: false,
      // 股票历史减持列表数据
      historyDataList: [],
      // 股票历史减持列表总行
      historyTotal: 0,
      // 上市项目options
      listedOptions: [],
      // 减持公告options
      noticeOptions: [],
      // 证券账号options
      securityOptions: [],
      // 交易对手options
      opponentOptions: [],
      // 减持公告是否展示
      noticeShow: false,
      // 历史股票减持查询条件
      queryParams: {
        listedId: '',
        shareId: '',
        pageNum: 1,
        pageSize: 10
      }
    }
  },
  mounted() {
    this.$bus.$emit('async_done')
  },
  created() {
    // 获取所有上市项目options
    listListedDeal({ dealType: (this.$route.query.dealType === undefined ? 'equity' : this.$route.query.dealType) }).then(response => {
      this.listedOptions = response.rows
    })
    // 获取证券账户options
    listListedSecurity({}).then(response => {
      this.securityOptions = response.rows
    })
    // 交易方式字典
    this.getDicts('listed_trading_way').then(response => {
      this.tradingWayOptions = response.data
    })
  },
  methods: {
    // 初始化数据
    init(data) {
      this.noticeShow = false
      if (data != null && data.id !== undefined) {
        this.loading = true
        getListedShareSub(data.id).then(response => {
          this.form = response.data
          this.selectListDeal()
          this.selectNotice()
          this.loading = false
        })
      } else {
        this.reset()
      }
    },
    // 获取股票历史减持信息
    getHistoryList() {
      this.historyLoading = true
      this.queryParams.shareId = this.form.id
      listHistory(this.queryParams).then(response => {
        this.historyDataList = response.rows
        this.historyTotal = response.total
        this.historyLoading = false
      })
    },
    // 交易方式字典翻译
    tradingWayFormat(row) {
      return this.selectDictLabel(this.tradingWayOptions, row.tradingWay)
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        listedId: undefined,
        dealName: undefined,
        stockCode: undefined,
        shareHold: undefined,
        shareRate: undefined,
        noticeId: undefined,
        dealType: (this.$route.query.dealType === undefined ? 'equity' : this.$route.query.dealType),
        shareNotExceeding: undefined,
        rateNotExceeding: undefined,
        releaseDate: undefined,
        reducingDateStart: undefined,
        reducingDateEnd: undefined,
        securityId: undefined,
        totalSubAmount: undefined,
        totalSubShare: undefined,
        subPrice: undefined,
        subTaxe: undefined,
        subFeeRate: undefined,
        tradingWay: undefined,
        subDate: undefined,
        opponentId: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        remark: undefined,
        detailList: []
      }
      this.historyDataList = []
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    // 计算减持均价
    calcSubPrice(index) {
      const totalSubAmount = this.form.detailList[index].totalSubAmount
      const totalSubShare = this.form.detailList[index].totalSubShare
      // 验证实际减持股数不能大于最大持有股数
      if (totalSubShare === undefined || totalSubShare === '' || totalSubShare === 0) {
        this.form.detailList[index].subPrice = 0.0
        return
      }
      if (totalSubAmount === undefined || totalSubAmount === '') {
        this.form.detailList[index].subPrice = 0.0
        return
      }
      if (totalSubShare > this.form.shareHold) {
        this.msgError('本次减持股数不能大于项目持有股数！')
        this.form.detailList[index].totalSubShare = ''
        return
      }
      this.form.detailList[index].subPrice = totalSubAmount / totalSubShare / 10000
      // 计算减持费率
      this.calcSubFeeRate(index)
    },
    // 计算减持费率
    calcSubFeeRate(index) {
      const totalSubAmount = this.form.detailList[index].totalSubAmount
      const subTaxe = this.form.detailList[index].subTaxe
      if (totalSubAmount !== undefined && totalSubAmount !== '' && subTaxe !== undefined && subTaxe !== '' && totalSubAmount !== 0) {
        this.form.detailList[index].subFeeRate = subTaxe / totalSubAmount * 100
      } else {
        this.form.detailList[index].subFeeRate = 0.0
      }
    },
    // 根据上市项目ID，获取持仓信息
    getSecurityByListedId() {
      this.queryParams.listedId = this.form.listedId
      listListedPositionHold(this.queryParams).then(res => {
        res.rows.forEach(item => {
          // 添加dataList 股票减持详情
          const row = {
            securityId: item.securityId,
            totalSubAmount: '',
            totalSubShare: '',
            subPrice: '',
            subTaxe: '',
            subFeeRate: '',
            tradingWay: '',
            subDate: new Date(),
            opponentId: ''
          }
          if (!(this.form.detailList instanceof Array)) {
            this.$set(this.form, 'detailList', [])
          }
          this.$nextTick(() => {
            this.form.detailList.push(row)
          })
        })
      })
    },
    // 选择上市项目事件，获取选择的项目的其他关联数据
    selectListDeal() {
      // 获取关联数据
      getListedDeal(this.form.listedId).then(res => {
        this.form.stockCode = res.data.stockCode
        this.form.shareHold = res.data.shareHold
        this.form.shareRate = res.data.shareRate
        this.form.dealId = res.data.dealId
        this.form.dealName = res.data.dealName
        this.noticeShow = res.data.shareRate > 5
        // 获取股票历史减持信息
        this.queryParams.listedId = this.form.listedId
        this.getHistoryList()
        // 获取减持公告options
        listListedReducingNotice(this.queryParams).then(res => {
          this.noticeOptions = res.rows
        })
        // 获取交易对手options
        listListedBusinessOpponent(this.queryParams).then(res => {
          this.opponentOptions = res.rows
        })
        if (this.form.id === undefined || this.form.id === '') {
          this.form.detailList = []
          // 获取当前上市项目的持仓证券股数
          this.getSecurityByListedId()
        }
      })
    },
    // 选择减持公告事件，获取选择的公告的其他关联数据
    selectNotice() {
      // 获取关联数据
      getListedReducingNotice(this.form.noticeId).then(res => {
        if (res.data) {
          this.form.shareNotExceeding = res.data.shareNotExceeding
          this.form.rateNotExceeding = res.data.rateNotExceeding
          this.form.releaseDate = res.data.releaseDate
          this.form.reducingDate = this.parseTime(res.data.reducingDateStart) + '  ~  ' + this.parseTime(res.data.reducingDateEnd)
        }
      })
    },
    /** 提交按钮 */
    submitForm: function(type) {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(valid => {
          if (valid) {
            this.loading = true
            saveListedShareSub(this.form).then(response => {
              if (response.code === 200) {
                if (type === 'process') {
                  // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                  this.form.id = response.data
                  // 启动流程
                  this.startProcess(response.data)
                } else {
                  this.msgSuccess(this.$t('保存成功'))
                  this.closeForm()
                }
                resolve()
              } else {
                this.msgError(response.msg)
                this.loading = false
                reject()
              }
              this.loading = false
            })
          } else {
            reject()
            this.locationError(document)
          }
        })
      })
    },
    // 启动流程
    startProcess: function(dataId) {
      this.loading = false
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      processData.title = this.form.dealName + ' - 股票减持申请'
      // 业务表名
      processData.dataTable = 'listed_share_sub'
      // 业务ID
      processData.dataId = dataId
      // 业务表单地址
      processData.formPath = '@/views/deal/listed/shareSub/listedShareSubForm'
      processData.viewPath = '@/views/deal/listed/shareSub/listedShareSubView'
      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.menuKey = this.menuKey
      this.startProcessByMenu(processData, () => {
        this.form.actStatus = 'D'
        this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
        this.closeForm()
      })
    }
  }

}
</script>
